$(function () {
    //获取设备类型
    login.deviceType = common.checkMobile();
    //关闭语音播报队列
    Voice.cancel();
    //热重启问题
    if (loginStatus == "yes" && userInfor) {
        let username = native.getDataByKey('username');
        let password = native.getDataByKey('password');
        if (username != undefined) {
            jQuery("#login-form input[name='accout']")[0].value = username;
        }
        if (password != undefined) {
            jQuery("#login-form input[name='password']")[0].value = password;
        }

        let IS_OFFLINE_MODULE = native.getDataByKey("IS_OFFLINE_MODULE");
        if (IS_OFFLINE_MODULE == "1") {
            login.signIn();
        } else {
            //调接口判断是不是已经在别的设备登陆
            Dao.findOrgByOrgCode({
                userName: userInfor.accountName,
                deviceId: appKeyObj.deviceId,
                orgCode: platformCode || app.data.defaultPlatCode
            }, function (re) {
                setTimeout(function () {
                    if (username != undefined && password != undefined) {
                        login.signIn();
                    }
                }, 200);
            }, null, function () {
                app.methods.showToastCenter("您已登陆其他设备");
            });
        }
    } else {
        //退出登录之后
        if (native.getDataByKey('username') != undefined) {
            jQuery("#login-form input[name='accout']")[0].value = native.getDataByKey('username');
        }
        if (native.getDataByKey('password') != undefined) {
            jQuery("#login-form input[name='password']")[0].value = native.getDataByKey('password');
        }
    }

    $('#login-form input[name="accout"],#login-form input[name="password"]').keypress(function (e) {
        //enter查询
        if (e.which == 13) {
            login.signIn();
        };
    });

    login.intIphoneInputPopup()

    if(location.href.indexOf('http')==0){
        native.saveDataByKey('locationOrigin',location.origin)
    }

});

var login = (function (_self) {
    _self.cdCode = null; //验证码倒计时定时器
    _self.cdModifyPwSuc = null; //修改成功返回登录定时器
    _self.currentPhone = "";
    _self.deviceType = "";
    //_self.currentCode ="000000";//当前验证码

    _self.signIn = function () {
        var formData = app.form.convertToData('#login-form');
        var username = jQuery.trim(formData.accout);
        var password = jQuery.trim(formData.password);
        if (username == "" || password == "") {
            app.methods.showToastCenter("请输入帐号和密码！");
            return;
        }
        if (username.indexOf(" ") != -1) {
            app.methods.showToastCenter("用户名输入有误！");
            return;
        }
        common.loading(1);

        let parserLoginResult = function (data) {
            var IS_OFFLINE_MODULE = native.getDataByKey("IS_OFFLINE_MODULE");//离线维保
            var OFFLINE_SELECT_ORGID = native.getDataByKey("OFFLINE_SELECT_ORGID");
            var IS_OFFLINE_DAYCHECK = native.getDataByKey("IS_OFFLINE_DAYCHECK");
            var IS_OFFLINE_DAYWEIBAO = native.getDataByKey("IS_OFFLINE_DAYWEIBAO");
            if (IS_OFFLINE_MODULE == "1") {
                app.router.navigate("/offlineWork/" + OFFLINE_SELECT_ORGID + "/" + IS_OFFLINE_DAYCHECK + "/" + IS_OFFLINE_DAYWEIBAO + "/");
            }
            userStartTime = moment().format("YYYY-MM-DD HH:mm:ss");
            let isHasUserLimit = false;
            //判断用户角色
            if (data.role.length > 0) {
                for (let i = 0; i < data.role.length; i++) {
                    if (jQuery.inArray(data.role[i].id, userIdObj) > -1) {
                        isHasUserLimit = true;
                        break;
                    }
                }
            }
            if (isHasUserLimit) {
                if (data.resources && data.resources.length < 1) {
                    app.methods.showToastCenter("无数据权限");
                    common.loading(0);
                    return;
                }
                //用户信息存储
                userInfor = data;
                platformCode = userInfor.loginId;
                app.data.defaultPlatCode = userInfor.loginId;
                
                selectVenuesIdByAccount(function(){
                    setTimeout(res => {
                        Dao.getExamDetailByExamAccount({ examAccount: userInfor.accountName }, function (res) {
                            if (res) {
                                let id = res.id
                                let html = `<div class ="pupbg"style="position: absolute;
                                            left: 0;
                                            top: 0;
                                            width: 100%;
                                            height: 100%;
                                            background: rgba(0,0,0,.4);
                                                z-index: 10500;">
                                            </div>
                                            <div class ="pupText" style="left: 5%;
                                            border-bottom-left-radius: 15px;
                                            border-bottom-right-radius: 15px;
                                            bottom: 20px;
                                            width: 90%;
                                            z-index: 13000;
                                            background-color:#FFFFFF;
                                            position:absolute;">
                                                <div>
                                                <div >
                                                <div style="text-align:center"> 
                                                <p><i class="iconfont icon-gantanhao-" style="color:#F3BC32;font-size:60px;"></i>
                                                </p>您当前有未完成的考试</p>
                                                </div>
                                                <div style="display:flex;justify-content: space-between;align-items:center;margin-top: 51px;">
                                                <div class="confirmSubmit" style="  flex:1;
                                                margin-right:20px;
                                                    border-radius:4px;
                                                    height: 44px;
                                                    line-height: 44px;
                                                    border:1px solid rgba(225,225,225,1);
                                                    display: inline-block;
                                                    text-align: center;    border-bottom-left-radius: 15px;
                                                ">确定提交</div>
                                                    <div class="continueSubmit" style="    display: inline-block;
                                                    text-align: center;flex:1;
                                                    height:44px;
                                                    line-height: 44px;
                                                    background:rgba(36,113,202,1);
                                                    border-radius:4px;
                                                    color: #FFFFFF; border-bottom-right-radius: 15px;">继续答题</div>
                                                    </div>
                                            </div>
                                            </div>`;
                                jQuery('body').append(html)
    
                                jQuery('.confirmSubmit').click(function () {
                                    jQuery('.pupText').hide()
                                    let html = `<div class="puptexttotal" style=" width: 90%;
                                                z-index: 13000;
                                                background-color:#FFFFFF;
                                                left:5%;
                                                top:40%;
                                                padding:20px 0;
                                                border-radius:15px;
                                                position:absolute;"><p style="text-align:center;"><i class="iconfont icon-duigou" style="font-size:60px;color:rgba(105, 186, 113, 1)"></i></p>
                                                <p style="text-align:center;"> 已交卷，正在计算得分...</p></div>`
                                    $('body').append(html)
                                    Dao.submitExam({ examDetailId: id }, function () {
                                        setTimeout(res => {
                                            jQuery('.puptexttotal').hide()
                                            jQuery('.pupbg').hide()
                                            app.router.navigate(`/examResult/${id}`);
                                        }, 3000)
    
                                    })
                                })
    
                                jQuery('.continueSubmit').click(function () {
                                    jQuery('.pupText').hide()
                                    jQuery('.pupbg').hide()
                                    app.router.navigate(`/examPage/${id}`);
                                })
    
                            }
                        })
                    })
                    if (userInfor.role[0].id == 143) {
                        //九小编码信息获取
                        if (nineCode) {
                            currentUseOrgIds = userInfor.organizationIds;
                            native.setUserInfor(data);
                            userLoggedIn = true;
                            native.saveDataByKey('username', username);
                            native.saveDataByKey('password', password);
                            native.saveDataByKey('loginStatus', 'yes'); //保存登录状态 登录成功yes 退出登录no
    
                            if (data.isMuilUnitUser == 1) { //多联网单位角色
                                single_Orgid = "";
                                single_OrgName = "";
                            } else { //单联网单位角色
                                single_Orgid = data.org.id;
                                single_OrgName = data.org.name;
                            }
                            initPage();
                            $(".login-quit-btn").html("登录中...");
                            setTimeout(function () {
                                $(".login-quit-btn").html("登录");
                            }, 1200);
                            if (userInfor.accountName == "review" || userInfor.accountName == "review_yq" || userInfor.accountName == "review_qy") {
                                app.router.navigate("/verifierInfo/''/");
                            } else {
                                if (viewHref != '') {
                                    app.router.navigate(viewHref);
                                    viewHref = '';
                                }
                            }
                        } else {
                            app.methods.showToastCenter("该用户未关联权限");
                            setTimeout(native.logOut(), 3000);
                        }
                        common.loading(0);
                    } else {
                        currentUseOrgIds = userInfor.organizationIds;
                        native.setUserInfor(data);
                        userLoggedIn = true;
                        native.saveDataByKey('username', username);
                        native.saveDataByKey('password', password);
                        native.saveDataByKey('loginStatus', 'yes'); //保存登录状态 登录成功yes 退出登录no
                        if (data.isMuilUnitUser == 1) { //多联网单位角色
                            single_Orgid = "";
                            single_OrgName = "";
                        } else { //单联网单位角色
                            single_Orgid = data.org.id;
                            single_OrgName = data.org.name;
                        }
                        initPage();
                        $(".login-quit-btn").html("登录中...");
                        setTimeout(function () {
                            $(".login-quit-btn").html("登录");
                        }, 1200);
                        if (viewHref != '') {
                            app.router.navigate(viewHref);
                            viewHref = '';
                        }
                    }
                });
            } else {
                app.methods.showToastCenter("用户角色有误");
                common.loading(0);
                return;
            }
            
            // 关闭登录页
            app.popup.close(".login-popup", false);

        }

        let IS_OFFLINE_MODULE = native.getDataByKey("IS_OFFLINE_MODULE");
        if (userInfor && (IS_OFFLINE_MODULE == "1")) {
            parserLoginResult(userInfor);
        } else {
            app.request({
                url: contextPath + "app/user/login",
                dataType: "json",
                contentType: "application/json",
                method: 'post',
                async: false,
                data: _self.transParam({
                    userName: username,
                    password: jQuery.md5(password),
                    isAlicloud: appKeyObj.isAlicloud ? appKeyObj.isAlicloud :0,
                    deviceId: appKeyObj.deviceId,
                    systemContext: appKeyObj.systemContext ? appKeyObj.systemContext : "",
                    deviceType: _self.deviceType,
                    loginId: platformCode || app.data.defaultPlatCode
                }),
                success: function (data) {
                    Dao.transSucData(function (data) {
                        parserLoginResult(data);
                    }, data);
                },
                error: function (xhr) {
                    common.loading(0);
                    app.methods.showToastCenter("登录失败");
                }
            });
        }

    }

    _self.transParam = function (ajaxParam) {
        var sysP = {};
        var navP = ajaxParam;
        navP.deviceId = appKeyObj.deviceId;
        sysP.requestTime = Date.parse(new Date());
        sysP.appKey = appKeyObj.appKey;
        sysP.sign = Dao.signParam(navP, sysP.requestTime);
        return JSON.stringify({
            sysParams: sysP,
            params: navP
        });
    }

    // get参数格式化
    _self.transGetParam = function (ajaxParam) {
        var sysP = {};
        var navP = ajaxParam;
        navP.deviceId = appKeyObj.deviceId;
        sysP.requestTime = Date.parse(new Date());
        sysP.appKey = appKeyObj.appKey;
        sysP.sign = Dao.signParam(navP, sysP.requestTime);
        return {
            sysParams: JSON.stringify(sysP),
            params: JSON.stringify(navP)
        };
    }

    _self.backToLogin = function (subPageType) {
        if (subPageType == 1) {
            app.popup.close(".popup-bindWx");
        } else {
            app.loginScreen.close();
        }
    }

    _self.showForgetForm = function () {
        var formData = app.form.convertToData('#login-forget-form');
        for (var Key in formData) {
            formData[Key] = "";
        }
        app.form.fillFromData('#login-forget-form', formData);
        clearTimeout(_self.cdCode);
        clearTimeout(_self.cdModifyPwSuc);
        _self.currentPhone = "";
        $(".btn-vCode").removeAttr("disabled").html("获取验证码");
        setTimeout(() => {
            jQuery("#login-forget-form input").val("")
        }, 500);
    }

    _self.getvCode = function () {
        var formData = app.form.convertToData('#login-forget-form');
        var phone = formData.phone;
        if (!common.isMobile(phone)) {
            app.methods.showToastCenter("请输入有效的手机号码！");
            return;
        }
        _self.currentPhone = phone;
        common.loading(1);
        Dao.getSmsCode({
            mobile: phone,
            type: 1
        }, function (data) {
            common.loading(0);
            _self.get_code_time($(".btn-vCode"), 60);
            //_self.currentCode = data;
            app.methods.showToastCenter("请于60s内填入有效验证码");
        }, function (data) {
            common.loading(0);
            app.methods.showToastCenter("获取验证码失败");
        });
    },
        _self.saveNewPw = function () {
            var formData = app.form.convertToData('#login-forget-form');
            if (formData.phone == "") {
                app.methods.showToastCenter("请输入有效的手机号码！");
                return;
            }
            if (_self.currentPhone == "") {
                app.methods.showToastCenter("请重新获取验证码！");
                return;
            }
            if (formData.phone != _self.currentPhone) {
                app.methods.showToastCenter("两次手机号不一致！");
                return;
            }
            if (formData.code == "" /*_self.currentCode*/) {
                app.methods.showToastCenter("请输入有效的验证码！");
                return;
            }
            if (formData.pw1 == "" || formData.pw2 == "") {
                app.methods.showToastCenter("密码不能为空！");
                return;
            }
            if (formData.pw1 != formData.pw2) {
                app.methods.showToastCenter("确认密码不一致！");
                return;
            }
            for (var Key in formData) {
                jQuery.trim(formData[Key]);
            }
            common.loading(1);
            Dao.forgetPwd({
                mobile: formData.phone,
                code: formData.code,
                type: 1,
                newPassword: jQuery.md5(formData.pw1)
            }, function (data) {
                common.loading(0);
                app.methods.showToastCenter("修改成功！", 800);
                native.saveDataByKey('password', formData.pw1);
                userInfor ? (userInfor.password = jQuery.md5(formData.pw1).toUpperCase()) : '';
                _self.cdModifyPwSuc = setTimeout(function () {
                    app.loginScreen.close();
                }, 1000)
            }, function (data) {
                common.loading(0);
                app.methods.showToastCenter("修改密码失败");
            });
        }

    //倒计时功能
    _self.get_code_time = function ($input, wait) {
        if (wait == 0) {
            $input.removeAttr("disabled");
            $input.html("重新发送");
            wait = 60;
        } else {
            $input.attr("disabled", true);
            $input.html(wait + "s");
            wait--;
            _self.cdCode = setTimeout(function () {
                _self.get_code_time($input, wait);
            }, 1000)
        }
    }

    //ios上h5的输入框被弹起的解决方法
    _self.intIphoneInputPopup = function(){
        if (login.deviceType == 2) {//安卓
            
        } else if (login.deviceType == 1) {//防止ios软键盘把页面挤上去，表单不在视野范围内
            if (!isDebug && !/MicroMessenger/.test(window.navigator.userAgent)) {//检测非真机根据localhost判断、微信端
                document.addEventListener(
                    'blur',
                    event => {
                            // 当页面没出现滚动条时才执行，因为有滚动条时，不会出现这问题
                            // input textarea 标签才执行，因为 a 等标签也会触发 blur 事件
                        if (
                            document.documentElement.offsetHeight <=
                            document.documentElement.clientHeight &&
                            ['input', 'textarea'].includes(event.target.localName)
                        ) {
                            document.body.scrollIntoView() // 回顶部
                        }
                    },
                    true
                )
            }
        }
    }

    return _self;
})(window.login || {});
